package com.laoye.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.laoye.Exception.exception.BaseException;
import com.laoye.annotation.Log;
import com.laoye.bean.Admin;
import com.laoye.dto.*;
import com.laoye.mapper.AdminMapper;
import com.laoye.service.AdminService;
import com.laoye.util.EmailUtil;
import com.laoye.util.Page;
import com.laoye.util.ThreadLocal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class AdminServiceImpl implements AdminService {
    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

@CacheEvict(value = "userInfo",allEntries = true)
    @Override
@Log("管理员删除用户信息")
    public void updateUser(Integer id) {
    if (id == null){
        throw new BaseException(401, "用户ID不能为空");
    }
        adminMapper.updateUser(id);  //取消删除用户
    }
    @Cacheable(
            value = "userInfo",
            // Key 格式：userList_查询类型_关键词_是否删除_页码_页大小（处理null参数）
            key = "'userList_' + #queryType + '_' + (#keyword ?: 'null') + '_' + (#is_deleted ?: 'null') + '_' + #pageNum + '_' + #pageSize",
            unless = "#result == null || #result.getTotal() == 0" // 空数据不缓存（避免缓存穿透）
    )
    @Override
    public PageInfo<Admin_UserInfo> getAllUserInfo(String queryType,
                                                         String keyword,
                                                         Integer is_deleted,
                                                         Integer pageNum,
                                                         Integer pageSize) {
        // 设置分页参数
        PageHelper.startPage(pageNum, pageSize);
        // 执行查询
        List<Admin_UserInfo> userInfoList = adminMapper.getUserInfo(queryType, keyword, is_deleted);
        //3.封装分页结果（PageInfo自动计算总记录数和总页数）
        PageInfo<Admin_UserInfo> pageInfo = new PageInfo<>(userInfoList);
        Page<Admin_UserInfo> userPages = Page.<Admin_UserInfo>builder()
                .list(userInfoList)
                .total(pageInfo.getTotal())
                .totalPages(pageInfo.getPages())
                .pageNum(pageInfo.getPageNum())
                .pageSize(pageInfo.getPageSize())
                .build();
        // 包装成PageInfo对象返回
        return new PageInfo<>(userInfoList);
    }

    @Override
    @Cacheable(
            value = "adminInfo",
            // Key 格式：adminList_查询类型_关键词_页码_页大小（公共数据，无当前管理员ID）
            key = "'adminList_' + #queryType + '_' + (#keyword ?: 'null') + '_' + #pageNum + '_' + #pageSize",
            unless = "#result == null || #result.getTotal() == 0"
    )
    public Page<Admin_UserInfo> getAllAdmins(String queryType, String keyword, Integer pageNum, Integer pageSize) {
        // 设置分页参数
        PageHelper.startPage(pageNum, pageSize);
        // 执行查询
        List<Admin_UserInfo> AdminList = adminMapper.getAdmins(queryType, keyword);
        //3.封装分页结果（PageInfo自动计算总记录数和总页数）
        PageInfo<Admin_UserInfo> pageInfo = new PageInfo<>(AdminList);
        Page<Admin_UserInfo> userPages = Page.<Admin_UserInfo>builder()
                .list(AdminList)
                .total(pageInfo.getTotal())
                .totalPages(pageInfo.getPages())
                .pageNum(pageInfo.getPageNum())
                .pageSize(pageInfo.getPageSize())
                .build();
        // 包装成PageInfo对象返回
        return userPages;
    }

    @Override
    @Log("管理员登录")
    public Admin login(LoginDTO loginDTO) {
        // 检查输入参数
        if (loginDTO == null || loginDTO.getUsername() == null || loginDTO.getPassword() == null) {
            throw new BaseException(401, "用户名或密码不能为空");
        }

        // 先根据用户名查找用户
        Admin admin = adminMapper.login(loginDTO);

        // 检查用户是否存在
        if (admin == null) {
            throw new BaseException(401, "管理员不存在");
        }

        // 验证密码是否正确
        boolean matches = passwordEncoder.matches(loginDTO.getPassword(), admin.getPassword());
        if (!matches) {
            throw new BaseException(401, "密码错误");
        }

        return admin;
    }

    @Override
    @Log("管理员修改密码")
    public void updatePassword(PwdEditDTO pwdEditDTO) {
    if (pwdEditDTO == null || pwdEditDTO.getId() == null || pwdEditDTO.getOldPassword() == null || pwdEditDTO.getNewPassword() == null) {
        throw new BaseException(401, "用户ID、旧密码或新密码不能为空");
    }
        pwdEditDTO.setId(ThreadLocal.getCurrentId());
        String encode = passwordEncoder.encode(pwdEditDTO.getNewPassword());
        pwdEditDTO.setNewPassword(encode);
        adminMapper.updatePassword(pwdEditDTO);
        String email = adminMapper.getEmail(ThreadLocal.getCurrentId());
        EmailUtil.sendEmail(email,
                "管理员先生您好，您的密码修改成功，请确保是您本人操作，新的密码为:"+pwdEditDTO.getNewPassword()+",请勿泄露");
    }


    @Override
    @Log("管理员登出")
    public void logout() {
        ThreadLocal.removeCurrentId();
    }

    /**
     * 拉黑用户
     *
     * @param id 用户id
     */
    @CacheEvict(value = "userInfo",allEntries = true)
    @Override
    @Log("管理员拉黑用户")
    public void deleteUser(Integer id) {
        if (id == null){
            throw new BaseException(401, "用户ID不存在");
        }
        adminMapper.deleteUser(id);
    }


    @CacheEvict(
            value = {"adminInfo","admin"},
            allEntries = true // 编辑后清理管理员列表、名称、头像缓存
    )
    @Override
    @Log("管理员编辑自身信息")
    public void editAdmin(UserEditDTO userInfo) {
        if (userInfo == null || userInfo.getId() == null){
            throw new BaseException(401, "用户信息不能为空");
        }
        Integer currentId = ThreadLocal.getCurrentId();
        userInfo.setId(currentId);
        adminMapper.editAdmin(userInfo);
    }


    @Cacheable(
            value = "adminName",
            // Key 格式：adminName_目标管理员ID（与查询参数id绑定）
            key = "'adminName_' + #id",
            unless = "#result == null || #result.isEmpty()"
    )
    @Override
    public String findAdminName(Integer id) {
        if (id == null){
            throw new BaseException(401, "管理员id不能为空");
        }
        return adminMapper.findAdminName(id);
    }



    @CacheEvict(
            value = "adminAvatar",
            // Key 格式：adminAvatar_目标管理员ID（与参数id绑定）
            key = "'adminAvatar_' + #id"
    )
    @Override
    @Log("管理员修改头像")
    public void updateAvatar(String file, Integer id) {
        if (file == null || id == null){
            throw new BaseException(401, "头像上传参数错误");
        }
        adminMapper.updateAvatar(file, id);
    }



    @Cacheable(
            value = "adminAvatar",
            key = "'adminAvatar_' + #id",
            unless = "#result == null || #result.isEmpty()"
    )
    @Override
    public String getAvatarUrl(Integer id) {
        if (id == null){
            throw new BaseException(401, "管理员id不能为空");
        }
        return adminMapper.getAvatarUrl(id);
    }



    @Cacheable(value = "admin",key = "T(com.laoye.util.ThreadLocal).getCurrentId()",unless = "#result == null")
    @Override
    public Admin getAdminById() {
        return adminMapper.getAdminById(ThreadLocal.getCurrentId());
    }

}
